package com.yc.fedex.exceptions;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.fedex.mapper.FedexJsonMapper;
import com.yc.fedex.model.error.FedexErrorsRoot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedList;
import java.util.List;

public class FedexErrorCodeFactory {
    private static final Logger LOGGER = LoggerFactory.getLogger(FedexErrorCodeFactory.class);
    private static final String COULD_NOT_PARSE_ERROR_RESPONSE_MESSAGE = "Could not parse error message from fedex for response body: {}";

    private FedexErrorCodeFactory() {
    }

    public static List<FedexError> create(final String responseBody) {
        List<FedexError> fedexErrorCodes = new LinkedList<>();
        try {
            ObjectMapper jsonMapper = FedexJsonMapper.buildMapper();
            FedexErrorsRoot fedexErrorsRoot = jsonMapper.readValue(responseBody, FedexErrorsRoot.class);
            fedexErrorCodes = fedexErrorsRoot.getErrors();
        } catch (final Exception e) {
            final FedexError fedexError = new FedexError("UNKNOWN", responseBody);
            fedexErrorCodes.add(fedexError);
            LOGGER.warn(COULD_NOT_PARSE_ERROR_RESPONSE_MESSAGE, responseBody, e);
        }
        return fedexErrorCodes;
    }

}
